package com.bsoft.servicetest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import com.socks.library.KLog;

import java.util.Date;

/**
 * Created by 泅渡者
 * Created on 2017/9/21.
 */

public class WeatherService extends Service {

    private static final int NOTIFY_KEY = 0x11;

    @Override
    public void onCreate() {
        super.onCreate();
        showNotifycation();
        KLog.d("被执行");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        KLog.d("被执行");
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Into the Senate :
     * Return:
     * 显示通知
     */
    private void showNotifycation() {
        NotificationCompat.Builder mBilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.icon_weather)
                .setContentTitle(new Date().toString())
                .setContentText("今天天气晴");
        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent requestPending = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        mBilder.setContentIntent(requestPending);

        NotificationManager mNotify = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        final Notification notify = mBilder.build();

        mNotify.notify(NOTIFY_KEY, notify);

        //启动前台服务
        startForeground(NOTIFY_KEY, notify);
        KLog.d("被执行");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        KLog.d("被执行");
    }
}
